package com.tang.thepath;

import android.Manifest;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;

import com.tang.thepath.util.CoordinateUtil;


public class UploadLocationService extends Service {

    private LocationManager locationManager;
    private String locationProvider = LocationManager.NETWORK_PROVIDER;
    private static long MIN_TIME = 1000;
    private static float MIN_DISTANCE = 0;
    private boolean isRequesting = false;
    private Context context;
    private String currentProvider;
    private int minTime = 60000*1;//1分钟

    public static final String BROADCAST_REQUEST_LOCATION_ACTION = "com.tang.action.REQUEST_LOCATION_UPDATE";
    public static final String BROADCAST_PROVIDER_DISABLED_ACTION = "com.tang.action.LOCATION_PROVIDER_DISABLED";
    public static final String BROADCAST_PROVIDER_ENABLED_ACTION = "com.tang.action.LOCATION_PROVIDER_ENABLED";
    public static final String TAG = "UploadLocationService";

    private Thread requestThread;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            if (message.what == 1) {
                if (ActivityCompat.checkSelfPermission(UploadLocationService.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                        && ActivityCompat.checkSelfPermission(UploadLocationService.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
                locationManager.requestLocationUpdates(currentProvider, 5, MIN_DISTANCE, mListener);
            }
            return false;
        }
    });

    private Runnable requestLocation = new Runnable() {
        @Override
        public void run() {
            try{
                while (true){
                    handler.sendEmptyMessage(1);
                    Thread.sleep(minTime);
                }
            }catch (InterruptedException e) {
                e.printStackTrace();
                locationManager.removeUpdates(mListener);
            }

        }
    };


    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (this.isRequesting) {
            return super.onStartCommand(intent, flags, startId);
        }

        String provider = intent.getStringExtra("provider");

        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            Toast.makeText(this,"服务启动失败:获取定位权限不足",Toast.LENGTH_SHORT).show();
            return super.onStartCommand(intent, flags, startId);
        }

        currentProvider = provider;
        if(provider.equals("gps")){
            locationManager.requestLocationUpdates(provider, minTime, MIN_DISTANCE, mListener);
        }else if(provider.equals("network")){
            requestThread = new Thread(requestLocation);
            requestThread.start();
        }

        this.isRequesting = true;

        Intent intent1 = new Intent(this,MainActivity.class);
        intent1.addCategory("android.intent.category.DEFAULT");
        intent1.setAction("com.tang.thepath.MainActivity");
        PendingIntent pintent= PendingIntent.getService(this, 0, intent1, 0);
        Notification mNotification = new Notification.Builder(UploadLocationService.this)
                .setAutoCancel(false)
                .setContentTitle("后台服务")
                .setContentText("已启动")
                .setContentIntent(pintent)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.location))
                .setSmallIcon(R.drawable.location)
                .setWhen(System.currentTimeMillis())
                .build();

//        Notification notification = new Notification(R.drawable.ic_launcher,
//                "wf update service is running",
//                System.currentTimeMillis());
//
//        notification.setLatestEventInfo(this, "WF Update Service",
//                "wf update service is running！", pintent);

        //让该service前台运行，避免手机休眠时系统自动杀掉该服务
        //如果 id 为 0 ，那么状态栏的 notification 将不会显示。
        startForeground(startId, mNotification);

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        if(locationManager != null){
            locationManager.removeUpdates(mListener);
        }
        if(requestThread != null && requestThread.isAlive()){
            requestThread.interrupt();
            requestThread = null;
        }
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

//    LocationListener locationListener = new LocationListener(){
//        // 当位置发生变化时触发
//        public void onLocationChanged(Location location) {
//            Log.i(TAG, "时间："+location.getTime());
//            Log.i(TAG, "经度："+location.getLongitude());
//            Log.i(TAG, "纬度："+location.getLatitude());
//            Log.i(TAG, "海拔："+location.getAltitude());
//        }
//        // 当GPS关闭时触发
//        public void onProviderDisabled(String arg0) {
//        }
//        // 当GPS开启时触发
//        public void onProviderEnabled(String arg0) {
//        }
//        // 当位置状态改变时触发
//        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
//            switch (status) {
//                //GPS状态为可见时
//                case LocationProvider.AVAILABLE:
//                    Log.i(TAG, "当前GPS状态为可见状态");
//                    break;
//                //GPS状态为服务区外时
//                case LocationProvider.OUT_OF_SERVICE:
//                    Log.i(TAG, "当前GPS状态为服务区外状态");
//                    break;
//                //GPS状态为暂停服务时
//                case LocationProvider.TEMPORARILY_UNAVAILABLE:
//                    Log.i(TAG, "当前GPS状态为暂停服务状态");
//                    break;
//            }
//        }
//    };

    protected LocationListener mListener = new LocationListener() {
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

            Log.e(TAG,"onStatusChanged:"+status);
        }

        @Override
        public void onProviderEnabled(String provider) {
            Log.e(TAG,"onProviderEnabled:"+provider);

            //发送一个广播通知整个应用
            Intent intent = new Intent();
            intent.putExtra("provider", provider);
            intent.setAction(BROADCAST_PROVIDER_ENABLED_ACTION);
            sendBroadcast(intent);
        }

        @Override
        public void onProviderDisabled(String provider) {
            Log.e(TAG,"onProviderDisabled:"+provider);

            //发送一个广播通知整个应用
            Intent intent = new Intent();
            intent.putExtra("provider", provider);
            intent.setAction(BROADCAST_PROVIDER_DISABLED_ACTION);
            sendBroadcast(intent);
        }

        // 如果位置发生变化，重新显示
        @Override
        public void onLocationChanged(Location location) {
            Log.e("UploadLocationService","LOCATION:"+location.getLatitude()+"-"+location.getLongitude());

            //转换坐标
            double[] latlng = CoordinateUtil.transformFromWGSToGCJ(location);
            //发送一个广播通知整个应用
            Intent intent = new Intent();
            //Double latitude=location.getLatitude();
            //Double longitude=location.getLongitude();
            Double latitude=latlng[0];
            Double longitude=latlng[1];
            intent.putExtra("lat", latitude);
            intent.putExtra("lng",longitude);
            intent.setAction(BROADCAST_REQUEST_LOCATION_ACTION);
            sendBroadcast(intent);

            //因为network每一段时间手动获取
            if(currentProvider.equals("network")){
                locationManager.removeUpdates(mListener);
            }
        }
    };




}
